package com.minivision.fdiot.service;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.codec.Utf8;
//import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import com.minivision.fdiot.common.AuthParam;
import com.minivision.fdiot.entity.AppInfo;
import com.minivision.fdiot.entity.FaceSet;
import com.minivision.fdiot.exception.ErrorType;
import com.minivision.fdiot.exception.FacePlatException;
import com.minivision.fdiot.repository.mysql.AppRepository;
import com.minivision.fdiot.repository.redis.FaceSetRepository;
import com.minivision.fdiot.rest.param.app.AppCreateParam;
import com.minivision.fdiot.rest.param.app.AppUpdateParam;
import com.minivision.fdiot.rest.result.app.AppCreateResult;
import com.minivision.fdiot.rest.result.app.AppUpdateResult;

@Service 
public class AppServiceImpl extends BaseService implements AppService {

  @Autowired 
  private AppRepository appRepository;

  @Autowired 
  private FaceSetRepository setRepository;

  //@Autowired private Md5PasswordEncoder md5Encoder;

  @Autowired 
  private FaceSetService faceSetService;

  /**
   * 获取应用创建的所有人脸库
   * @param appKey
   * @return
   */
  private List<FaceSet> findFaceSetsByApp(String appKey) {
    List<FaceSet> faceSets = setRepository.findByAppKeyEquals(appKey);
    return faceSets;
  }

  /**
   * 创建应用
   */
  @Override 
  public AppCreateResult create(AppCreateParam param) {
    AppInfo appInfo = new AppInfo();
    /*appInfo.setAppKey(md5Encoder.encodePassword(param.getAppName(),
            param.getAppSecret() + ":" + System.currentTimeMillis()));*/
    appInfo.setAppKey(DigestUtils.md5DigestAsHex(Utf8.encode(param.getAppName() + "{" + param.getAppSecret() + ":" + System.currentTimeMillis() + "}")));
    BeanUtils.copyProperties(param, appInfo);
    AppInfo created = appRepository.save(appInfo);
    return new AppCreateResult(created.getId(), created.getAppKey());
  }

  /**
   * 更新应用信息
   */
  @Override 
  public AppUpdateResult update(AppUpdateParam param) throws FacePlatException {
    AppInfo appInfo = appRepository.findByAppKey(param.getAppKey());
    AppInfo app = appRepository.findByAppNameEquals(param.getAppName());
    if (app != null && appInfo.getId().equals(app.getId())) {
      throw new FacePlatException(ErrorType.APP_NAME_REPEATED);
    }
    appInfo.setAppName(param.getAppName());
    if (StringUtils.hasText(param.getAppSecret())) {
      appInfo.setAppSecret(param.getAppSecret());
    }
    AppInfo updated = appRepository.save(appInfo);
    return new AppUpdateResult(updated.getId(), updated.getAppName(), updated.getAppKey());
  }

  /**
   * 删除应用
   */
  @Override
  public void delete(AuthParam appDelParam) throws FacePlatException {
    try {
      appRepository.deleteByAppKey(appDelParam.getAppKey());
      List<FaceSet> faceSets = findFaceSetsByApp(appDelParam.getAppKey());
      for (FaceSet faceSet : faceSets) {
        //cascade delete face
        faceSetService.delete(faceSet.getFacesetToken(), true, appDelParam.getAppKey(),appDelParam.isNeedPush2Device());
      }
    } catch (RuntimeException e) {
      throw new FacePlatException(ErrorType.SERVER_ERROR);
    }
  }

  /**
   * 获取应用信息
   */
  @Override 
  public AppInfo getDetail(AuthParam param) {
    AppInfo appInfo = appRepository.findByAppKey(param.getAppKey());
    List<FaceSet> faceSets = setRepository.findByAppKeyEquals(param.getAppKey());
    appInfo.setFaceSets(faceSets);
    return appInfo;
  }
}
